app.controller('AccumulationDataTableController', AccumulationDataTableController);
function AccumulationDataTableController($rootScope, $scope, $modal, HospitalFactory,OperationTimeFactory, RESTService, $filter,$compile) {
    // define value
    $scope.limitPatCase = 5; // case limit to 5 for one operation item
    $scope.status = "needope";
    $scope.searchKey = "";

	$scope.assignedCount = 0;
	
    // define value for hospital
    $scope.ArrHospital = [];
    $scope.ArrCountry= [];
    $scope.ArrProvince= [];
    $scope.ArrCity= [];
    $scope.ArrCounty= [];
    $scope.ArrHospLevel = [];

    //
    $scope.dtInstanceServRequest =  $scope.dtInstanceHospital = null;
    // paging for service request
    $scope.dtOptions = {
        aaSorting: [],
        bFilter: false,
        bLengthChange: false,
        bSort: false,
        bStateSave: false,
        oLanguage: {
            sUrl: ("Cn" === $scope.locale ? "./l10n/datatables.Chinese.json" : "")
        },
        processing: true,
        serverSide: true,
        sAjaxDataProp: "data",
        ajax: function(data, callback) {
            console.log('data:',data);
            $scope.servRequests = [];
            getCountServRequest();
            // prepare query variables
            var params = {
                status : $scope.status,
                like: $scope.searchKey,
                pageNo: data.start / data.length + 1,
                pageSize: data.length
            };
            var sort = [], i;

            if (0 !== data.order.length) {
                for (i in data.order) {
                    if (data.order.hasOwnProperty(i)) {
                        sort.push({
                            property: data.columns[data.order[i].column].data,
                            direction: data.order[i].dir.toUpperCase()
                        });
                    }
                }

                if (0 !== sort.length) {
                    params.sort = angular.toJson(sort);
                }
            }

            if (3 <= data.search.value.length) {
                params.filter = data.search.value;
            }
            // transmit to server
            RESTService.getResponse("/rest/servreq/getServReqs?" + $.param(params)).then(
                function(response) {
                    angular.forEach(response, function(item) {
                        item.No =   $scope.servRequests.length  + (params.pageNo * params.pageSize) - 9;
                        $scope.servRequests.push(item);
                    });
                    callback({
                        aaData: [],
                        draw: data.draw,
                        recordsTotal: $scope.rowCount,
                        recordsFiltered: $scope.rowCount
                    });
                    if ($scope.dtInstanceServRequest == null) {
                        $scope.dtInstanceServRequest = _.clone($scope.dtInstance);
                    }
                    $scope.dtInstanceServRequest.find("td.dataTables_empty").parent().hide(); // small hack for "aaData: []"
                });
        },
        fnCreatedRow: function(row) {
            $compile(row)($scope);
        },
        fnInitComplete: function() {
            $scope.$parent.dtInstance = this.fnSetFilteringDelay();
        }
    };
    $rootScope.$watch('selectLang',function(newValue){
        $scope.dtOptions.oLanguage.sUrl = ("Cn" === $scope.locale ? "./l10n/datatables.Chinese.json" : "")
        // $scope.dtOptions = $scope.dtOptions;
        // $scope.dtOptions.ajax(data, callback);

    },true);
    // action list for service request
    function getCountServRequest(){
        var param = {
            status : $scope.status,
            like: $scope.searchKey
        };
        RESTService.getResponse("/rest/servreq/getServReqsCount?" + $.param(param)).then(function(response){
            if(undefined !== response){
                $scope.rowCount = response[0].count;
            }
        });
    }
    $scope.startSearch = function(searchkey){
        $scope.searchKey = searchkey;
        $scope.dtInstanceServRequest.DataTable().ajax.reload();
    };
	
    // action list for hospital
    $scope.getOperationCenters = function() {
        $scope.ArrHospital = [];
        var params = {
            hospLevel_Id: 0,
            province_Id: 0,
            country_Id : 38 ,
            county_Id : 0,
            city_Id: 0,
            flag: true,
            opeCenTime: true
        };
        HospitalFactory.getCount(params).then(function(response) {
            if (undefined !== response) {
                params.pageNo = 0;
                params.pageSize =response[0].count;
                HospitalFactory.getPage(params).then(
                    function(response) {
                        angular.forEach(response, function(item) {
                            var hosp = HospitalFactory.SetHospital(item);
                            $scope.ArrHospital.push(hosp);
                        });
                        InitOpenOpeCenTime();
                        InitSurgeon();
                    });
            }
        });
    }
    function InitOpenOpeCenTime(){
        $scope.ArrOpeCenTimes = [];
        var param = {};
        $scope.assignedCount = 0;
        OperationTimeFactory.getActiveOperationTimes(param).then(function(response){
            if(undefined !== response){
                $scope.ArrOpeCenTimes = response;
                angular.forEach($scope.ArrHospital, function(hosp){
                    var opetime = $filter('filter')($scope.ArrOpeCenTimes, function(time) {
                        return (time._hosp)?time._hosp.hosp_Id === hosp.hosp_Id:false; });
                    hosp.OpeCentTime = (opetime.length > 0)?opetime:[];
                    angular.forEach(hosp.OpeCentTime, function(oct) {
	                    $scope.assignedCount += oct.count;
	                });
                });
            }
        });
    }
    function InitSurgeon(){
        $scope.ArrSurgeon = [];
        var param = {
            userRole : 'Surgeon',
            like :'',
            pageNo : 1,
            pageSize : 20
        };
        RESTService.getResponse("/rest/user/getUsers?" + $.param(param)).then(function(response){
            if(undefined !== response){
                $scope.ArrSurgeon = response;
            }
        });
    }
    $scope.resetFilter = function(){
        $scope.optionFilter = {
            hospLevel_Id: 0,
            province_Id: 0,
            country_Id : 38 ,
            county_Id : 0,
            city_Id: 0
        };
    };
    $scope.getHospitalLevels = function() {
        var params = {};
        RESTService.getResponse("/rest/hosplevel/getHospLevels?" + $.param(params), null, null).then(function(response) {
            if (undefined !== response) {
                angular.forEach(response,function(arrays){
                    $scope.ArrHospLevel.push(arrays);
                });
            }
        });
    };
    // main action for page
    $scope.open = function(attrs, model) {
        // model.scope = $scope;
        $modal.open(angular.extend({
            backdrop:'static',
            controller: "ModalInstanceCtrl",
            resolve: {
                items: function() {
                    return [Object(model)];
                }
            },
            scope : $scope
        }, attrs));
    };
    function reloadData (){
        if($scope.dtInstanceServRequest != null){
            $scope.dtInstanceServRequest.DataTable().ajax.reload();
        }
        $scope.getOperationCenters();
    }
    
    // add a new OCT
    $scope.openAddOCT = function() {
		$scope.loadingHospital = true;
		var params = {
            hospLevel_Id: 0,
            province_Id: 0,
            country_Id : 38 ,
            county_Id : 0,
            city_Id: 0,
            flag: true,
			pageNo: 0,
            pageSize: 5000
        };
		HospitalFactory.getPage(params).then(	 
			function(response) {
				var modalInstance = $modal.open({
                    backdrop:'static',
					templateUrl: 'AddOCT.html',
					controller: 'ModalInstanceCtrl',
					size: 'md',
					resolve: {
						items: function() {
						return  response;
						}
					}
				});
				$scope.loadingHospital = false;
				modalInstance.result.then(function(item) {
					var param = {
						hosp_Id: item.hosp_Id
					};
					RESTService.postResponse("/rest/opecentime/createOpeCenTime?", param).then(function(response) {
						if (undefined !== response) {
							$scope.getOperationCenters();
						}
					});	//ok click
				}, function() {
					//cancel
				});
			}
		);
			
    };
    $scope.DetailServRequest = function(item) {
        $scope.SelectedRequest = item;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'DetailServRequest.html',
            controller: 'ModalInstanceCtrl',
            size: 'lg',
            resolve: {
                items: function() {
                    return  $scope.SelectedRequest;
                }
            }
        });
        modalInstance.result.then(function() {
            $scope.SelectedRequest= {};
        }, function() {
            $scope.SelectedRequest= {};
            //cancel
        });
    };
    $scope.AssignToOpeCenTimePopup = function(item) {
        $scope.SelectedRequest = item;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'AssignOpeTime.html',
            controller: 'ModalInstanceCtrl',
            size: 'md',
            resolve: {
                items: function() {
                    return  $filter('filter')($scope.ArrOpeCenTimes,function(ope){ return ope.count <= $scope.limitPatCase; });
                }
            }
        });
        modalInstance.result.then(function(selectedOperationTimeId) {
            if(selectedOperationTimeId > 0){
                $scope.assignServReq(selectedOperationTimeId, $scope.SelectedRequest.servReq_Id );
            }
            //ok click
        }, function() {
            $scope.SelectedRequest= {};
            //cancel
        });
    };

	// assign a surgeon to OCT
	// entrance: openAssignSurgeon
	// call: setSurgeon(id of OCT, userId of surgeon)    
    $scope.openAssignSurgeon = function(item) {
        $scope.SelectedOpeCenTime = item;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'AssignSurgeon.html',
            controller: 'ModalInstanceCtrl',
            size: 'lg',
            resolve: {
                items: function() {
                    return {
                    	surgeons : $scope.ArrSurgeon,
                    	opeCenTime_Id : $scope.SelectedOpeCenTime.opeCenTime_Id
                    }
                }
            }
        });
        modalInstance.result.then(function(userId) {
            //ok click
        }, function() {
        InitOpenOpeCenTime();
            $scope.startSearch();
            $scope.dtInstanceHospital.DataTable().ajax.reload();
            //cancel
        });
    };
    $scope.setSurgeon = function (opeCenTime_Id, userId){
        if(opeCenTime_Id > 0 && userId > 0){
            var param = {
                    opeCenTime_Id: opeCenTime_Id,
                    userId: userId
            };
            RESTService.postResponse("/rest/opecentime/setSurgeon?", param).then(function(){
            	$scope.cancel();
            });
        }
    };
    
    // add a new servReq to OCT
    // entrance: openAssignServReq(item)
    // call: assignServReq(id of OCT, id of servReq)
    $scope.openAssignServReq = function(item) {
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'AssignServRequest.html',
            controller: 'ModalInstanceCtrl',
            size: 'lg',
            resolve: {
                items: function() {
                    return  item;
                }
            }
        });
        modalInstance.result.then(function() {
            //ok click
        }, function() {
            InitOpenOpeCenTime();
            $scope.startSearch();
            // $scope.dtInstanceHospital.DataTable().ajax.reload();
            //cancel
        });
    };
    $scope.assignServReq = function (opeTimeId, serRequestId){
        if(opeTimeId > 0 && serRequestId > 0){
            var param = {
                servReq_Id: serRequestId,
                opeCenTime_Id:opeTimeId
            };
            RESTService.postResponse("/rest/servreq/assignOpeCenTime?", param).then(function(){
                reloadData()
            });
        }
    };
    
    // entrance: setTimeOfOCT
    $scope.setTimeOfOCT = function (item){
    	$scope.minDate=moment(new Date()).format("YYYY-MM-DD");
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'TimeOfOCT.html',
            controller: 'ModalInstanceCtrl',
            size: 'sm',
            resolve: {
                items: function() {
                    return item;
                }
            }
        });
        modalInstance.result.then(function(date) {
            if (date != null && date !== undefined) {
                var param = {
                    date_Operation: moment(date).format("YYYY-MM-DD"),
                    opeCenTime_Id : item.opeCenTime_Id
                };
                RESTService.postResponse("/rest/opecentime/setDate?", param).then(function(response){
                    if(undefined !== response){
                        InitOpenOpeCenTime();
                    }
                });
            }
            //ok click
        }, function() {
            $scope.SelectedRequest = {};
            //cancel
        });

    };
    
    // RefuseForOperation
    // entrance: openRefuseForOperation(servReq)
    // call: refuseForOperation(servReq)
	$scope.openRefuseForOperation = function(servReq) {
		$scope.servReq = servReq;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'RefuseForOperation.html', controller: 'ModalInstanceCtrl', size: 'md', resolve: {
            	items: function() {
            		return $scope.servReq;
                }
            }
        });		
        modalInstance.result.then(function() {
        	$scope.refuseForOperation($scope.servReq);
        }, function() {
        });
    }
    $scope.refuseForOperation  = function(serv){
        var param = {
            servReq_Id: serv.servReq_Id
        };
        RESTService.postResponse("/rest/servreq/setRefuseForOpe?", param, true).then(function(response) {
            if (response.code == 0) {
                $scope.dtInstanceServRequest.DataTable().ajax.reload();
            }
        });
    };
    
	
	// delete one OCT
	// entrance: openDeleteOCT(OCT)
	// action: deleteOCT(OCT)
	$scope.openDeleteOCT = function(opeCenTime) {
		$scope.opeCenTime = opeCenTime;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'DeleteOCT.html', controller: 'ModalInstanceCtrl', size: 'md', resolve: {
            	items: function() {
            		return $scope.opeCenTime;
                }
            }
        });		
        modalInstance.result.then(function() {
        	$scope.deleteOCT($scope.opeCenTime);
        }, function() {
        });
    }
    $scope.deleteOCT = function(item) {
        var param = {
            opeCent_Id: item.opeCenTime_Id
        };
        RESTService.postResponse("/rest/opecentime/deleteOpeCenTime?", param, true).then(function(response) {
            if (response.code == 0) {
               reloadData();
            }
        });
    };
    
	
	// finish one OCT
	// entrance: openFinish(OCT)
	// action: finishOpeCenTime
	$scope.openFinishOCT = function(opeCenTime) {
		$scope.opeCenTime = opeCenTime;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'FinishOCT.html', controller: 'ModalInstanceCtrl', size: 'md', resolve: {
            	items: function() {
            		return $scope.opeCenTime;
                }
            }
        });		
        modalInstance.result.then(function() {
        	$scope.finishOCT($scope.opeCenTime);
        }, function() {
        });
    }
    $scope.finishOCT = function(item) {
        var param = {
            opeCenTime_Id: item.opeCenTime_Id
        };
        RESTService.postResponse("/rest/opecentime/finish?", param, true).then(function(response) {
            if (response.code == 0) {
                reloadData();
            }
        });
    };

	// Revoke servReq from OCT
	// entrance: openRevokeFromOCT(servReq, servReqs_Of_OCT)
	// action: revokeFromOCT
	$scope.openRevokeFromOCT = function(servReq, servReqsOfOCT) {
		$scope.servReq = servReq;
		$scope.servReqsOfOCT = servReqsOfOCT;
        var modalInstance = $modal.open({
            backdrop:'static',
            templateUrl: 'openRevokeFromOCT.html', controller: 'ModalInstanceCtrl', size: 'md', resolve: {
            	items: function() {
            		return $scope.servReq;
                }
            }
        });		
        modalInstance.result.then(function() {
        	$scope.revokeFromOCT($scope.servReq, $scope.servReqsOfOCT);
        }, function() {
        });
    }
    $scope.revokeFromOCT = function(serv, servReqsOfOCT){
            var param = {
                servReq_Id: serv.servReq_Id
            };
            RESTService.postResponse("/rest/servreq/revokeOpeCenTime?", param, true).then(function(response) {
            	// console.log("response: ", response);
                if (response.code == 0) {
                    servReqsOfOCT.splice(servReqsOfOCT.indexOf(serv),1);
                }

            });
    };

    // share case
    $scope.sharePatient = function(a, b){
        var patient_Id = a.patient_Id ? a.patient_Id : a.patient_Id2;
        var params = {
            patient_Id:patient_Id
            ,friendId:b
        }
        console.log(params);
        RESTService.postResponse('/rest/chat/createChatMessageSharingPatient?', params).then(
            function (suc) {
                console.log(suc);
            });
    }
}